//
//  InsideViewController.m
//  day-02-TopView
//
//  Created by hcios on 2017/6/30.
//  Copyright © 2017年 hcios. All rights reserved.
//

#import "InsideViewController.h"
#import "WeatherCityModel.h"
#import "FoldHeaderView.h"
#import "AFNetworking.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height

@interface InsideViewController ()<UITableViewDelegate,UITableViewDataSource,FoldHeaderViewDelegate>{
    
    NSMutableArray *_dataSeactionArray;
    NSMutableArray *_dataSeactionNameArray;
    
    UITableView *_tableView;
}


@property(nonatomic,strong) NSMutableDictionary *foldInfoDic;   //存储开关字典

@end

@implementation InsideViewController

#pragma mark - init初始化
-(instancetype)init{
    self = [super init];
    
    if (self) {
        _dataSeactionArray = [[NSMutableArray alloc] init];
        _dataSeactionNameArray = [[NSMutableArray alloc] init];
    }
    return self;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initTable];
    [self netWorking];
}


#pragma mark - 初始化tableView
-(void)initTable{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 106) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
}


#pragma mark - UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataSeactionArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSString *key = [NSString stringWithFormat:@"%d",(int)section];
    
    BOOL folded = [[_foldInfoDic objectForKey:key] boolValue];
    
    NSInteger count = [_dataSeactionArray[section] count];
    if (folded == YES) {
        return 0;
    }else return count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *cellId = [NSString stringWithFormat:@"cellID%ld%ld",(long)[indexPath section],(long)[indexPath row]];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    
    WeatherCityModel *model = _dataSeactionArray[indexPath.section][indexPath.row];
    cell.textLabel.text = model.city_name_zh_cn;
    NSLog(@"%@",model.items_count);
    return cell;
}


#pragma mark - UItableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}

//点击
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"%ld%ld",(long)[indexPath section],(long)[indexPath row]);
    [self dismissViewControllerAnimated:YES completion:nil];
    WeatherCityModel *model = _dataSeactionArray[indexPath.section][indexPath.row];
    //注册通知改变view
    [[NSNotificationCenter defaultCenter] postNotificationName:@"change" object:model.city_id];
    //注册通知改变btn
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Btn" object:model.city_name_zh_cn];
    
}


#pragma mark - headerView
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    FoldHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    if (headerView == nil) {
        headerView = [[FoldHeaderView alloc] initWithReuseIdentifier:@"header"];
        [headerView setWeatherSectionHeaderViewWithTitle:_dataSeactionNameArray[section] detail:nil type:HeaderStyleNone section:section canFold:YES];
    }else{
        [headerView setWeatherSectionHeaderViewWithTitle:_dataSeactionNameArray[section] detail:nil type:HeaderStyleNone section:section canFold:YES];
    }
    headerView.delegate = self;
    NSString *key = [NSString stringWithFormat:@"%d",(int)section];
    BOOL folded = [[_foldInfoDic valueForKey:key] boolValue];
    headerView.fold = folded;
    return headerView;
    
}


#pragma mark - WeatherFoldHeaderViewDelegate
//代理
-(void)foldHeaderInSection:(NSInteger)SectionHeader{
    
    NSString *key = [NSString stringWithFormat:@"%d",(int)SectionHeader];
    BOOL folded = [[_foldInfoDic objectForKey:key] boolValue];
    NSString *fold = folded ? @"0" : @"1";
    [_foldInfoDic setValue:fold forKey:key];
    NSMutableIndexSet *set = [[NSMutableIndexSet alloc] initWithIndex:SectionHeader];
    
    //刷新section
    [_tableView reloadSections:set withRowAnimation:UITableViewRowAnimationAutomatic];
}


#pragma mark - netWorking
-(void)netWorking{
    
    NSString *urlString = @"http://chanyouji.com/api/wiki/destinations.json";
    NSDictionary *param = @{
                            @"page":@"1"
                            };
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:urlString parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //1.
        for (NSDictionary *dict in responseObject) {
            NSMutableDictionary *mutDict = [[NSMutableDictionary alloc] initWithDictionary:dict];
            //判断找出属于国内的分类
            if ([dict[@"category"] isEqualToString:@"99"] || [dict[@"category"] isEqualToString:@"999"]) {
                //2.取出每一个Section里的内容
                for (NSDictionary *dictDetail in mutDict[@"destinations"]) {
                    [_dataSeactionNameArray addObject:dictDetail[@"name_zh_cn"]];
                    NSMutableArray *rowArray = [[NSMutableArray alloc] init];
                    NSMutableDictionary *mutDictDetail = [[NSMutableDictionary alloc] initWithDictionary:dictDetail];
                    //3.取出每个row里的内容
                    for (NSDictionary *dictChild in mutDictDetail[@"children"]) {
                        WeatherCityModel *model = [[WeatherCityModel alloc] initWithDict:dictChild];
                        [rowArray addObject:model];
                    }
                    [_dataSeactionArray addObject:rowArray];
                }
            }
        }
        //找出选中国家的信息进行标记
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        for (int i = 0; i < _dataSeactionNameArray.count; i++) {
            [dict setObject:@"1" forKey:[NSString stringWithFormat:@"%d",i]];
        }
        _foldInfoDic = [NSMutableDictionary dictionaryWithDictionary:dict];
        //刷新tableView
        [_tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"网络请求失败");
    }];
}

@end
